package com.lanxiao.cloud.gateway.filter;

import com.lanxiao.cloud.gateway.provider.GatewaySwaggerProvider;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author ：qiaoliang
 * @date ：2021-08-24
 */
public class SwaggerHeaderFilter implements GlobalFilter {

  private static final String HEADER_NAME = "X-Forwarded-Prefix";

  @Override
  public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    ServerHttpRequest request = exchange.getRequest();
    String path = request.getURI().getPath();
    if (!StringUtils.endsWithIgnoreCase(path, GatewaySwaggerProvider.API_URI)) {
      return chain.filter(exchange);
    }
    String basePath = path.substring(0, path.lastIndexOf(GatewaySwaggerProvider.API_URI));
    ServerHttpRequest newRequest = request.mutate().header(HEADER_NAME, basePath).build();
    ServerWebExchange newExchange = exchange.mutate().request(newRequest).build();
    return chain.filter(newExchange);
  }
}
